<template>
  <div class="topcen">
    <div class="qiehuan">
      <div
        class="nianfen"
        :class="{ active: activeYear === '2020' }"
        @click="loadData('2020')"
      >
        2020
      </div>
      <div
        class="nianfen"
        :class="{ active: activeYear === '2021' }"
        @click="loadData('2021')"
      >
        2021
      </div>
      <div
        class="nianfen"
        :class="{ active: activeYear === '2022' }"
        @click="loadData('2022')"
      >
        2022
      </div>
      <div
        class="nianfen"
        :class="{ active: activeYear === '2023' }"
        @click="loadData('2023')"
      >
        2023
      </div>
      <div
        class="nianfen"
        :class="{ active: activeYear === '2024' }"
        @click="loadData('2024')"
      >
        2024
      </div>
    </div>
    <div class="box">
      <div class="topbox">
        <div id="main" style="width: 100%; height: 95%"></div>
        <div class="detailbox1">出口数量</div>
      </div>
      <div class="topbox">
        <div id="binphoto" style="width: 100%; height: 95%"></div>
      </div>
      <div class="topbox">
        <div class="xunhuan-container">
          <div class="xunhuan-list">
            <div
              class="xunhuan"
              v-for="(item, index) in mountlist"
              :key="index"
            >
              {{ mountyear[index] }}月 &nbsp;&nbsp;
              {{ address[index] }} &nbsp;&nbsp; {{ jj[index] + "人民币" }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="box">
      <div id="dynamic-line-chart" style="width: 100%; height: 95%"></div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";

const get2020cometoplist = ref([]);
const provinces = ref([]);
const totalQuantities = ref([]);
let myChart = null;
let binChartInstance = null;
const activeYear = ref("2020");

// 月份数据
const mountlist = ref([]);
const address = ref([]);
const mountyear = ref([]);
const jj = ref([]);

// 每年进口总数量变化
// const countyear = ref([])
// const mountnum = ref([])
const countyear = ref([]);

// 省份排行
const loadData = async (year) => {
  // 清除缓存
  get2020cometoplist.value = [];
  provinces.value = [];
  mountlist.value = [];
  mountyear.value = [];
  jj.value = [];
  address.value = [];

  activeYear.value = year;
  const res = await axios.get(`http://127.0.0.1:5000/api/data/${year}outtop`);
  // console.log(res.data,'111111111111111111')
  get2020cometoplist.value = res.data;
  provinces.value = get2020cometoplist.value.map(
    (item) => item[`${year}outtop.province`]
  );
  totalQuantities.value = get2020cometoplist.value.map(
    (item) => item[`${year}outtop.total_quantity`]
  );
  initChart();
  binChart();
  getmount(year);
  // getyearcount(year)
};

// 每月省份数据
const getmount = async (year) => {
  // console.log(year)
  const res = await axios.get(
    `http://127.0.0.1:5000/api/data/${year}mountshujuout`
  );
  mountlist.value = res.data;
  address.value = res.data.map(
    (item) => item[`${year}mountshujuout.selling_province`]
  );
  mountyear.value = res.data.map((item) => item[`${year}mountshujuout.month`]);
  jj.value = res.data.map(
    (item) => item[`${year}mountshujuout.total_import_amount`]
  );

  const monthlyQuantities = {};
  res.data.forEach((item) => {
    const month = item[`${year}mountshujuout.month`]; // 提取月份部分
    if (!monthlyQuantities[month]) {
      monthlyQuantities[month] = 0;
    }
    monthlyQuantities[month] +=
      item[`${year}mountshujuout.total_import_quantity`];
  });
  const monthlyQuantitiesArray = Object.keys(monthlyQuantities).map(
    (month) => ({
      month: parseInt(month),
      quantity: monthlyQuantities[month],
    })
  );
  monthlyQuantitiesArray.sort((a, b) => a.month - b.month);
  countyear.value = monthlyQuantitiesArray;
  movexian(countyear.value);
};

const initChart = () => {
  var chartDom = document.getElementById("main");
  if (chartDom) {
    if (myChart) {
      myChart.dispose();
    }
    myChart = echarts.init(chartDom);
    var option = {
      xAxis: {
        type: "category",
        data: provinces.value,
        axisLabel: {
          show: true,
          interval: 0,
          rotate: 45,
          margin: 10,
        },
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: totalQuantities.value,
          type: "bar",
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
            color: "#fff",
            fontSize: 12,
          },
        },
      ],
      animationDuration: 3000,
    };
    option && myChart.setOption(option);
  }
};

const binChart = () => {
  var chartDom = document.getElementById("binphoto");
  if (chartDom) {
    if (binChartInstance) {
      binChartInstance.dispose();
    }
    binChartInstance = echarts.init(chartDom);
    var option = {
      backgroundColor: "#1e1e1e",
      title: {
        text: " 进口占比",
        left: "center",
        top: 20,
        textStyle: {
          color: "#fff",
        },
      },
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          name: "Access From",
          type: "pie",
          radius: "55%",
          center: ["50%", "50%"],
          data: provinces.value
            .map((province, index) => ({
              name: province,
              value: totalQuantities.value[index],
            }))
            .sort((a, b) => a.value - b.value),
          roseType: "radius",
          label: {
            color: "rgba(255, 255, 255, 0.9)",
          },
          labelLine: {
            lineStyle: {
              color: "rgba(255, 255, 255, 0.9)",
            },
            smooth: 0.2,
            length: 10,
            length2: 20,
          },
          itemStyle: {
            color: "#5470c6",
            shadowBlur: 200,
            shadowColor: "rgba(0, 0, 0, 0.9)",
          },
          animationType: "scale",
          animationEasing: "elasticOut",
          animationDelay: () => Math.random() * 200,
        },
      ],
      animationDuration: 10000,
    };
    option && binChartInstance.setOption(option);
  }
};
// 动态曲线图
let dynamicLineChartInstance = null;

const movexian = (data) => {
  var chartDom = document.getElementById("dynamic-line-chart");
  if (chartDom) {
    if (dynamicLineChartInstance) {
      dynamicLineChartInstance.dispose();
    }
    dynamicLineChartInstance = echarts.init(chartDom);
    var option = {
      title: {
        text: "每年进出口数量变化",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: data.map((item) => item.month + "月"),
      },
      yAxis: {
        type: "value",
        name: "数量",
      },
      series: [
        {
          data: data.map((item) => item.quantity),
          type: "line",
          smooth: true,
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
            color: "#fff",
            fontSize: 12,
          },
        },
      ],
      animationDuration: 10000,
    };
    option && dynamicLineChartInstance.setOption(option);
  }
};

const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
  if (binChartInstance) {
    binChartInstance.resize();
  }
};

onMounted(() => {
  loadData("2020");
  getmount("2020");
  window.addEventListener("resize", resizeChart);
});

onUnmounted(() => {
  window.removeEventListener("resize", resizeChart);
  if (myChart) {
    myChart.dispose();
  }
  if (binChartInstance) {
    binChartInstance.dispose();
  }
});
</script>

<style scoped>
.topcen {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.qiehuan {
  width: 100%;
  display: flex;
  justify-content: space-around;
  height: 30px;
  line-height: 30px;
  margin-bottom: 10px;
  font-weight: 600;
  padding: 0 20px;
  cursor: pointer;
}

.active {
  color: #007bff;
  border-bottom: 1px solid #007bff;
}

.box {
  flex: 1;
  padding: 10px 20px;
  background-color: #1e1e1e;
  border: 1px solid #ccc;
  border-radius: 20px;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
}

.box:nth-child(1) {
  margin-bottom: 30px;
}

.topbox {
  width: 30%;
  border: 1px solid #ccc;
  box-sizing: border-box;
  border-radius: 10px;
  position: relative;
}

.detailbox1 {
  text-align: center;
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 5px 0;
  box-sizing: border-box;
}

.xunhuan-container {
  overflow: hidden;
  height: 100%;
  position: relative;
}

.xunhuan-list {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  animation: scroll 200s linear infinite;
}

@keyframes scroll {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-100%);
  }
}

.xunhuan {
  padding: 10px 10px;
  border: 2px solid #5470c6;
  margin: 20px 10px;
  border-radius: 10px;
}
</style>
